package org.codeart.serialize;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SerializeTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get("temp.obj")));
        oos.writeObject(Singleton.getInstance());
        File file = new File("temp.obj");
        ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(file.toPath()));
        Singleton singleton = (Singleton) ois.readObject();
        System.out.println(singleton);
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance() == singleton);
    }
}

class Singleton implements Serializable {

    private static volatile Singleton instance;

    private Singleton() {

    }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    // 解决方法：只需要在单例类定义readResolve方法，就可以解决序列化对单例模式破坏
    private Object readResolve() {
        return instance;
    }
}
